package online.sixfish.common.security;


import io.jsonwebtoken.ExpiredJwtException;
import online.sixfish.common.dto.UserDetail;
import online.sixfish.common.utils.JwtUtils;
import online.sixfish.common.utils.utils.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");
        if(token==null|| "null".equals(token)){
            filterChain.doFilter(request,response);
            return;
        }

        //存在token
        UserDetail userDetail=null;
        try {
            userDetail = JwtUtils.parseToken(token);

        } catch (ExpiredJwtException e){
            log.info("token过期",e);
            WebUtil.renderTokenExpired(response);
            return;
        }
        catch (Exception e) {
            log.info("解析token异常:{}",e);
            WebUtil.renderTokenError(response);
            return;
        }
        //存入SecurityContextHolder
        //获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userDetail, null,userDetail.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        log.info("权限:{}",userDetail.getAuthorities());
        filterChain.doFilter(request, response);



//        try {
//            if(isProtectedUrl(request)) {
////                System.out.println(request.getMethod());
//                if(!request.getMethod().equals("OPTIONS"))
//                    request = JwtUtil.validateTokenAndAddUserIdToHeader(request);
//            }
//        } catch (Exception e) {
//            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
//            return;
//        }
//        filterChain.doFilter(request, response);
    }



    public String removeBearerPrefix(String token) {
        if (token != null && token.startsWith("Bearer ")) {
            return token.substring(7); // 7是"Bearer "的长度
        }
        return token;
    }

}